package com.nowcoder.community.entity;

import lombok.Setter;

/**
 * 封装分页相关的信息
 * @author bombax
 * @date 2024-07-14 16:53
 */
public class Page {
    // 当前页码
    private int current = 1;
    // 显示的上限
    private int limit = 10;
    // 数据总数（用于计算总页数）
    private int rows;
    // 查询路径（用于复用分页链接）
    @Setter
    private String path;

    public void setCurrent(int current) {
        if(current >= 1) {
            this.current = current;
        }
    }

    public void setLimit(int limit) {
        if(limit >= 1 && limit <= 100) {
            this.limit = limit;
        }
    }

    public int getCurrent() {
        return current;
    }

    public int getLimit() {
        return limit;
    }

    public int getRows() {
        return rows;
    }

    public String getPath() {
        return path;
    }

    public void setRows(int rows) {
        if(rows >= 0) {
            this.rows = rows;
        }
    }

    /**
     * 获取当前页的起始行
     * @return current * limit - limit
     */
    public int getOffset() {
        return (current - 1) * limit;
    }

    /**
     * 获取总的页数
     * @return (rows + limit - 1) / limit
     */
    public int getTotal() {
        return (rows + limit - 1) / limit;
    }

    /**
     * 获取起始页码
     * @return
     */
    public int getFrom() {
        return Math.max(current - 2, 1);
    }

    /**
     * 获取结束页码
     * @return
     */
    public int getTo() {
        return Math.min(getTotal(), current + 2);
    }
}
